<template>
  <div>
    <!-- 头部面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addCate">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <tree-table
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        :show-index="true"
        index-text="#"
        border
        class="treetableTop"
      >
        <!-- 是否有效 -->
        <template slot="isok" slot-scope="scope">
          <i class="el-icon-success" v-if="scope.row.cat_deleted===false" style="color:lightgreen"></i>
          <i class="el-icon-error" v-if="scope.row.cat_deleted===true" style="color:red"></i>
        </template>
        <!-- 排序 -->
        <template slot="cateLevel" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level===0">一级</el-tag>
          <el-tag size="mini" type="success" v-if="scope.row.cat_level===1">二级</el-tag>
          <el-tag size="mini" type="warning" v-if="scope.row.cat_level===2">三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="opt" slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="showEditDialog(scope.row.cat_id)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="delCate(scope.row.cat_id)"
          >删除</el-button>
        </template>
      </tree-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2,5,10,15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加分类的对话框 -->
    <el-dialog title="提示" :visible.sync="showCatedialogVisible" width="50%" @close="closeAddCate">
      <el-form :model="cateForm" :rules="cateFormRules" ref="cateFormRef" label-width="100px">
        <el-form-item label="分类名称：" prop="cat_name" required>
          <el-input v-model="cateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类：">
          <el-cascader
            v-model="selectedKeys"
            :options="parentCateList"
            :props="{ expandTrigger: 'hover', ...cascaderProps}"
            @change="parentCateChanged"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showCatedialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCateConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="showEditCateDialog" width="50%" @close="closeEditCate">
      <el-form
        :model="editCateForm"
        :rules="editCateFormRules"
        ref="editCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称：" prop="cat_name" required>
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showEditCateDialog = false">取 消</el-button>
        <el-button type="primary" @click="editCateConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var checkCate = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入分类名称!"));
      }
      callback();
    };
    return {
      // 是否显示添加分类对话框
      showCatedialogVisible: false,
      columns: [
        {
          label: "分类名称",
          prop: "cat_name"
        },
        {
          label: "是否有效",
          // 定义当前列为模板列
          type: "template",
          // 表示当前这一列使用的模板名称
          template: "isok"
        },
        {
          lable: "排序",
          type: "template",
          template: "cateLevel"
        },
        {
          lable: "操作",
          type: "template",
          template: "opt"
        }
      ],
      // 商品类型总数量
      total: 0,
      // 查询条件
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 2
      },
      // 商品分类数据列表
      cateList: [],
      cateForm: {
        // 分类名称
        cat_name: "",
        // 父级分类的id
        cat_pid: 0,
        // 当前分类的等级
        cat_level: 0
      },
      cateFormRules: {
        cat_name: [{ validator: checkCate, trigger: "blur" }]
      },
      // 父级分类的列表
      parentCateList: [],
      // 定义级联组件的属性信息
      cascaderProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        checkStrictly: true
      },
      // 选中的父级分类的id数组
      selectedKeys: [],
      // 显示编辑分类的对话框
      showEditCateDialog: false,
      // 修改的form
      editCateForm: {},
      editCateFormRules: {
        cat_name: [
          {
            required: true,
            message: "请输入分类名称",
            trigger: "blur"
          }
        ]
      },
      // 被激活的页签的名称
      activeName: 'first',
    };
  },
  methods: {
    // tab 页签点击事件
    handleTabClick(){
      console.log(this.activeName)
    },
    // 删除分类
    async delCate(Id) {
      const resCf = await this.$msbox.confirm("确认删除id为" + Id + "的用户吗?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).catch(err=>err)
      if(resCf==='cancel') return this.$message.info('已取消删除')
      const {data: res} = await this.$http.delete('categories/'+Id)
      if(res.meta.status!==200) return this.$message.error('删除失败')
      this.getCateList()
      this.$message.success('删除成功')
    },
    // 点击编辑对话框的确定
    editCateConfirm() {
      this.$refs.editCateFormRef.validate(async valid => {
        if (!valid) return this.$message.error("表单验证未通过!");
        const { data: res } = await this.$http.put(
          `categories/${this.editCateForm.cat_id}`,
          {
            cat_name: this.editCateForm.cat_name
          }
        );
        console.log(res);
        if (res.meta.status !== 200) return this.$message.error("更新失败!");
        this.getCateList();
        this.$message.success("更新成功");
        this.showEditCateDialog = false;
      });
    },
    // 关闭编辑分类对话框
    closeEditCate() {
      this.editCateForm = {};
      this.$refs.editCateFormRef.resetFields();
    },
    // 根据cat_id查询分类
    async showEditDialog(Id) {
      const { data: res } = await this.$http.get(`categories/${Id}`);
      if (res.meta.status !== 200) return this.$message.error("获取分类失败");
      this.editCateForm = res.data;
      this.showEditCateDialog = true;
    },
    // 点击确认添加商品分类
    addCateConfirm() {
      this.$refs.cateFormRef.validate(async valid => {
        if (!valid) return this.$message.error("表单验证未通过!");
        const { data: res } = await this.$http.post(
          "categories",
          this.cateForm
        );
        if (res.meta.status !== 201) return this.$message.error("添加分类失败");
        console.log(res);
        this.getCateList();
        this.$message.success("添加分类成功!");
        this.showCatedialogVisible = false;
      });
    },
    // 当级联选择器改变后
    parentCateChanged() {
      let length = this.selectedKeys.length;
      if (length > 0) {
        this.cateForm.cat_pid = this.selectedKeys[length - 1];
        this.cateForm.cat_level = length;
      } else {
        this.cateForm.cat_pid = 0;
        this.cateForm.cat_level = 0;
      }
    },
    // 获取父级分类的数据列表
    async getCatePid() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 }
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取父级分类数据失败");
      this.parentCateList = res.data;
    },
    // 关闭分类对话框
    closeAddCate() {
      this.cateForm.cat_pid = 0;
      this.cateForm.cat_level = 0;
      this.cateForm.cat_name = "";
      this.selectedKeys = [];
      this.$refs.cateFormRef.resetFields();
    },
    // 添加分类
    addCate() {
      this.getCatePid();
      this.showCatedialogVisible = true;
    },
    // 当每页显示行数变化后
    handleSizeChange(val) {
      this.queryInfo.pagesize = val;
      this.getCateList();
    },
    // 查询当前页数据
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val;
      this.getCateList();
    },
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo
      });
      if (res.meta.status !== 200) this.$message.error("获取数据失败");
      this.cateList = res.data.result;
      this.total = res.data.total;
    }
  },
  created() {
    this.getCateList();
  }
};
</script>

<style lang='less' scoped>
.treetableTop {
  margin-top: 15px;
}
</style>